package com.dly.blog.service;

import com.dly.blog.domain.OpLogEntity;
import com.dly.blog.domain.ro.OpLogRO;
import com.dly.blog.domain.ro.PageRO;
import com.dly.blog.domain.vo.PageVO;
import com.dly.blog.inteface.LogStorageService;
import com.dly.blog.repository.OpLogRepository;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Queue;

/**
 * 日志保存 mongodb实现
 * @Author: DaiLiYu
 * @Date: 2023/7/17 11:31
 */
@Service
@AllArgsConstructor
public class MongodbLogStorageServiceImpl implements LogStorageService {

    private final OpLogRepository opLogRepository;

    private final MongoTemplate mongoTemplate;

    @Override
    public void saveLog(OpLogEntity opLogEntity) {
        opLogRepository.save(opLogEntity);
    }

    @Override
    public PageVO<OpLogEntity> getPageLog(OpLogRO pageRO) {
//        Page<OpLogEntity> all = opLogRepository.findAll(pageRO.buildPageRequest());
//        return PageVO.buildJPA(all,opLogEntity -> opLogEntity);
        Query query = new Query();
        if(Objects.nonNull(pageRO.getId())){
            query.addCriteria(Criteria.where("_id").is(pageRO.getId()));
        }
        if(Objects.nonNull(pageRO.getStartTime())){
            query.addCriteria(Criteria.where("startTime").gt(pageRO.getStartTime()));
        }
        if(Objects.nonNull(pageRO.getFinishTime())){
            query.addCriteria(Criteria.where("finishTime").lt(pageRO.getFinishTime()));
        }
        if(Objects.nonNull(pageRO.getMaxTime())){
            query.addCriteria(Criteria.where("consumingTime").lt(pageRO.getMaxTime()));
        }
        if(Objects.nonNull(pageRO.getMinTime())){
            query.addCriteria(Criteria.where("consumingTime").gt(pageRO.getMinTime()));
        }
        List<OpLogEntity> opLogEntities = mongoTemplate.find(query.with(pageRO.buildPageRequest()), OpLogEntity.class);
        long count = mongoTemplate.count(query, OpLogEntity.class);
        return new PageVO<>(pageRO.getCurrent(), pageRO.getSize(), count, opLogEntities);
    }

}
